package com.aicloud.gateway.aggregation.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import com.aicloud.gateway.aggregation.service.MoviesAndUsersAggregationService;
import com.aicloud.gateway.entity.User;
import com.google.common.collect.Maps;

import rx.Observable;
import rx.Observer;

/**
 * 聚合服务action
 * 
 * @author aaron
 * @varsion 0.1.0 2017年10月29日
 */
@RestController
public class MoviesAndUserAggregationController {
	private static final Logger			logger	= LoggerFactory.getLogger(MoviesAndUserAggregationController.class);

	@Autowired
	MoviesAndUsersAggregationService	aggService;

	/**
	 * 服务聚合访问入口
	 * 
	 * @return
	 */
	@GetMapping("/aggreate/{id}")
	public DeferredResult<Map<String, User>> aggregate(@PathVariable Long id) {
		Observable<HashMap<String, User>> result = this.aggregateObservable(id);
		return this.toDeferredResult(result);

	}

	/**
	 * 集合结果
	 * 
	 * @param id
	 * @return
	 */
	private Observable<HashMap<String, User>> aggregateObservable(Long id) {
		return Observable.zip(this.aggService.getUserById(id), this.aggService.getMovieUserById(id), (u1, u2) -> {
			HashMap<String, User> map = Maps.newHashMap();
			map.put("user", u1);
			map.put("movieUser", u2);
			return map;
		});
	}

	private DeferredResult<Map<String, User>> toDeferredResult(Observable<HashMap<String, User>> userDetail) {
		DeferredResult<Map<String, User>> result = new DeferredResult<>();
		userDetail.subscribe(new Observer<HashMap<String, User>>() {

			@Override
			public void onCompleted() {
				logger.info("Completed...");

			}

			@Override
			public void onError(Throwable e) {
				logger.error("发生异常...", e);

			}

			@Override
			public void onNext(HashMap<String, User> t) {
				result.setResult(t);
			}
		});
		return result;
	}

}
